﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Mvc;

using vuonthieunhi.Areas.Administration.Models;
using vuonthieunhi.Models;
using vuonthieunhi.Library;
using System.Collections;

namespace TSV.Areas.Administration.Controllers
{
    public class PartnerController : BaseController
    {
        private PartnerDao partnerDao = new PartnerDao();
        private PromotionDao promotionDao = new PromotionDao();
        private CategoryDao catDao = new CategoryDao();
        private DistrictDao distDao = new DistrictDao();
        private ProvinceDao proDao = new ProvinceDao();
        private GalleryDao galDao = new GalleryDao();
        //
        // GET: /Administration/Partner/

        public ActionResult Index()
        {
            int category = 0;
            if (Session["Filter"] != null)
            {
                Hashtable hash = (Hashtable)Session["Filter"];
                ViewData["text"] = hash["text"];
                category = Constants.ConvertToInt(hash["category"]);
                ViewData["sortColumn"] = hash["sortColumn"];
                ViewData["sortOder"] = hash["sortOder"];
                ViewData["page"] = hash["page"];
                ViewData["rowCount"] = hash["rowCount"];
            }
            else
            {
                ViewData["text"] = "Nhập tên";
                     ViewData["sortColumn"] = "ID";
                ViewData["sortOder"] = "asc";
                ViewData["page"] = "1";
                ViewData["rowCount"] = "30";
            }
            ViewData["CategoryList"] = new SelectList(catDao.GetList(), "ID", "CategoryName", category);
            return View();
        }

        private void SetSession(string text, string category, string sortColumn, string sortOder, string page, string rowCount)
        {
            Hashtable hash = new Hashtable();
            hash["text"] = text;
            hash["category"] = category;
            hash["sortColumn"] = sortColumn;
            hash["sortOder"] = sortOder;
            hash["page"] = page;
            hash["rowCount"] = rowCount;
            Session["Filter"] = hash;
        }

        /// <summary>
        /// Get and bind to grid
        /// </summary>
        /// <param name="optionSearch"></param>
        /// <returns></returns>
        public ActionResult GetListJQGrid(string name, string catId)
        {            
            //grid constant => duy hung
            #region JQGrid Params

            string sortColumn = (Request.Params[Constants.SORT_COLUMN]).ToString();
            string sortOrder = (Request.Params[Constants.SORT_ORDER]).ToString();
            int pageIndex = Convert.ToInt32(Request.Params[Constants.PAGE_INDEX]);
            int rowCount = Convert.ToInt32(Request.Params[Constants.ROW_COUNT]);

            #endregion
            SetSession(name,catId,sortColumn,sortOrder,pageIndex.ToString(),rowCount.ToString());
            #region search
            string text = null;
            int categoryId = 0;
            string searchName = string.Empty;
            if (!string.IsNullOrEmpty(name.Trim()) && !name.Trim().Equals("Nhập tên"))
            {
                text = name;
            }
            if (!string.IsNullOrEmpty(catId))
            {
                categoryId = int.Parse(catId);
            }
            #endregion

            List<sp_GetPartnerListResult> list = partnerDao.GetList(text, categoryId);

            int totalRecords = list.Count();
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rowCount);
            int currentPage = pageIndex;
            var finalList = list.Skip((currentPage - 1) * rowCount)
                                   .Take(rowCount);

            var jsonData = new
            {
                total = totalPages,
                page = currentPage,
                records = totalRecords,
                rows = (
                    from m in finalList
                    select new
                    {
                        i = m.ID,
                        cell = new string[] {
                            m.ID.ToString(),
                            "<img alt=\"Hình\" width=\"100px\" height=\"100px\" src=\"/FileUpload/Images/Partner/" + m.Logo + "\"/>",
                            m.CodeID,
                            HttpUtility.HtmlEncode(m.PartnerName),    
                             m.CurrentPrice.HasValue?m.CurrentPrice.Value.ToString():string.Empty,
                             m.OldPrice.HasValue?m.OldPrice.Value.ToString():string.Empty,
                             m.Quality.ToString(),
                            m.CategoryName,
                            "<a href='#' onclick=\"javascript:JS_LIB.redirect('/Administration/Partner/UpdateHotSales/?id=" + m.ID.ToString() + "')\">" + Constants.ShowActiveImage(m.IsHotSales) +"</a>",
                            "<a href='#' onclick=\"javascript:JS_LIB.redirect('/Administration/Partner/UpdateStatusNew/?id=" + m.ID.ToString() + "')\">" + Constants.ShowActiveImage(m.IsNew) +"</a>",
                             "<a href='#' onclick=\"javascript:JS_LIB.redirect('/Administration/Partner/UpdateStatusActive/?id=" + m.ID.ToString() + "')\">" + Constants.ShowActiveImage(m.DeleteFlag) +"</a>",
                            "<a href=\"#\" title=\"Cập nhật\" onclick=\"javascript:JS_LIB.redirect('/Administration/Partner/Edit/" + m.ID.ToString() + "')\" >Cập nhật</a>"
                        }
                    }
                ).ToArray()
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

       

        public ActionResult UpdateHotSales(string id)
        {
            if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(id))
            {
                Message msg = partnerDao.UpdateHotSales(int.Parse(id));
            }
            return RedirectToAction("Index");
        }

        public ActionResult UpdateStatusNew(string id)
        {
            if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(id))
            {
                Message msg = partnerDao.UpdateStatusNew(int.Parse(id));
            }
            return RedirectToAction("Index");
        }

        public ActionResult UpdateStatusActive(string id)
        {
            if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(id))
            {
                Message msg = partnerDao.UpdateStatusActive(int.Parse(id));
            }
            return RedirectToAction("Index");
        }
        
        //
        // GET: /Administration/Partner/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Administration/Partner/Create
        public ActionResult Create()
        {
            ViewData[CommonDataKey.CATEGORY] = new SelectList(catDao.GetList(), "ID", "CategoryName");
            ViewData["ManufacturerID"] = new SelectList(new ManufacturerDao().GetList(), "ID", "Name");
            return View();
        }

        //
        // POST: /Administration/Partner/Create

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(Partner obj)
        {
            try
            {
                // TODO: Add update logic here
                Message msg = partnerDao.Insert(obj);
                if (msg.MsgType == MessageType.Info)
                {
                    Stock objStock = new Stock();
                    objStock.PartnerID = obj.ID;
                    objStock.Quality = Constants.ConvertToInt(Request["Quality"]);
                    new StockDao().Update(objStock);
                    string tempPathLogo = Server.MapPath(Constants.UPLOAD_TEMP_PATH + obj.Logo);
                    string logoPathLogo = Server.MapPath(Constants.PHOTO_PATH_ROOT_PARTNER + obj.Logo);
                    if (System.IO.File.Exists(tempPathLogo))
                    {
                        System.IO.File.Move(tempPathLogo, logoPathLogo);
                    }

                    string tempPathBigImage = Server.MapPath(Constants.UPLOAD_TEMP_PATH + obj.BigImages);
                    string logoPathBigImage = Server.MapPath(Constants.PHOTO_PATH_ROOT_PARTNER + obj.BigImages);
                    if (System.IO.File.Exists(tempPathBigImage))
                    {
                        System.IO.File.Move(tempPathBigImage, logoPathBigImage);
                    }

                }
                ShowMessage(msg);

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Administration/Partner/Edit/5
        public ActionResult Edit(int id)
        {
            Partner partner = partnerDao.GetByID(id);
            ViewData[CommonDataKey.CATEGORY] = new SelectList(catDao.GetList(), "ID", "CategoryName",partner.CategoryID);
            ViewData["ManufacturerID"] = new SelectList(new ManufacturerDao().GetList(), "ID", "Name",partner.ManufacturerID);
            return View(partner);
        }

        //
        // POST: /Administration/Partner/Edit/5

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(Partner obj)
        {
            try
            {
                Message msg = partnerDao.Update(obj);
                Stock objStock = new Stock();
                objStock.PartnerID = obj.ID;
                objStock.Quality = Constants.ConvertToInt(Request["Quality"]);
                new StockDao().Update(objStock);
                string tempPathLogo = Server.MapPath(Constants.UPLOAD_TEMP_PATH + obj.Logo);
                string logoPathLogo = Server.MapPath(Constants.PHOTO_PATH_ROOT_PARTNER + obj.Logo);
                if (System.IO.File.Exists(tempPathLogo))
                {
                    System.IO.File.Move(tempPathLogo, logoPathLogo);
                }

                string tempPathBigImage = Server.MapPath(Constants.UPLOAD_TEMP_PATH + obj.BigImages);
                string logoPathBigImage = Server.MapPath(Constants.PHOTO_PATH_ROOT_PARTNER + obj.BigImages);
                if (System.IO.File.Exists(tempPathBigImage))
                {
                    System.IO.File.Move(tempPathBigImage, logoPathBigImage);
                }
                ShowMessage(msg);

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        public ActionResult DeleteList(string id)
        {
            Message msg = partnerDao.DeleteList(id);
            ShowMessage(msg);
            return RedirectToAction("Index");
        }

        //
        // GET: /Administration/Partner/Promotion/5
        public ActionResult Promotion(int id)
        {
            Partner partner = partnerDao.GetByID(id);
            if (partner != null)
            {
                ViewData["PartnerName"] = partner.PartnerName;
                ViewData["PartnerID"] = id.ToString();
            }
            return View();
        }

        /// <summary>
        /// Get and bind to grid
        /// </summary>
        /// <param name="optionSearch"></param>
        /// <returns></returns>
        public ActionResult GetListPromotionJQGrid(string id)
        {
            //grid constant => duy hung
            if (string.IsNullOrEmpty(id))
            {
                return null;
            }
            else
            {
                #region JQGrid Params

                string sortColumn = (Request.Params[Constants.SORT_COLUMN]).ToString();
                string sortOrder = (Request.Params[Constants.SORT_ORDER]).ToString();
                int pageIndex = Convert.ToInt32(Request.Params[Constants.PAGE_INDEX]);
                int rowCount = Convert.ToInt32(Request.Params[Constants.ROW_COUNT]);

                #endregion

                List<Promotion> list = promotionDao.GetListByPartnerID(int.Parse(id));

                int totalRecords = list.Count();
                int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rowCount);
                int currentPage = pageIndex;
                var finalList = promotionDao.Sort(list, sortColumn, sortOrder)
                                      .Skip((currentPage - 1) * rowCount)
                                       .Take(rowCount);

                var jsonData = new
                {
                    total = totalPages,
                    page = currentPage,
                    records = totalRecords,
                    rows = (
                        from m in finalList
                        select new
                        {
                            i = m.ID,
                            cell = new string[] {
                            m.ID.ToString(),
                            "<img alt=\"Hình\" width=\"100px\" height=\"100px\" src=\"/FileUpload/Images/Partner/" + m.Image + "\"/>",                            
                            HttpUtility.HtmlEncode(m.Title),        
                            "<input type=\"button\" class=\"icon edit\" title=\"Cập nhật\" onclick=\"JS_LIB.redirect('/Administration/Partner/EditPromotion/" + m.ID.ToString() + "')\" /> "                            
                        }
                        }
                    ).ToArray()
                };
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }
        }
        

        //
        // GET: /Administration/Partner/Promotion/5
        public ActionResult CreatePromotion(int id)
        {
            Partner partner = partnerDao.GetByID(id);
            if (partner != null)
            {
                ViewData["PartnerName"] = partner.PartnerName;
                ViewData["PartnerID"] = id.ToString();
            }            
            ViewData["LastOrder"] = promotionDao.GetLastOrder();
            return View();
        }

        //
        // GET: /Administration/Partner/Promotion/5
        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult CreatePromotion(Promotion promotion, FormCollection collection)
        {
            int lastOrder = int.Parse(collection["lastOrder"]);
            if (string.IsNullOrEmpty(collection["Photograph"]))
            {
                promotion.Image = "NoImage.jpg";
            }
            else
            {
                promotion.Image = collection["Photograph"];
            }
            promotion.PromotionOrder = lastOrder + 1;
            // TODO: Add update logic here
            Message msg = promotionDao.Insert(promotion);
            if (msg.MsgType == MessageType.Info)
            {
                string tempPathPhoto = Server.MapPath(Constants.UPLOAD_TEMP_PATH + promotion.Image);
                string logoPathPhoto = Server.MapPath(Constants.PHOTO_PATH_ROOT_PARTNER + promotion.Image);
                if (System.IO.File.Exists(tempPathPhoto))
                {
                    System.IO.File.Move(tempPathPhoto, logoPathPhoto);
                }

            }
            ShowMessage(msg);
            return RedirectToAction("Promotion/" + promotion.PartnerID);
        }

        public ActionResult EditPromotion(int id)
        {
            Promotion promotion = promotionDao.GetById(id);            
            if (promotion != null)
            {
                ViewData["PartnerName"] = promotion.Partner.PartnerName;                
            }
            
            return View(promotion);
        }

        //
        // GET: /Administration/Partner/Promotion/5
        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditPromotion(Promotion promotion, FormCollection collection)
        {
            promotion.ID = int.Parse(collection["PromotionID"]);
            if (string.IsNullOrEmpty(collection["Photograph"]))
            {
                promotion.Image = "NoImage.jpg";
            }
            else
            {
                promotion.Image = collection["Photograph"];
            }
            // TODO: Add update logic here
            Message msg = promotionDao.Update(promotion);
            ShowMessage(msg);
            return RedirectToAction("Promotion/" + promotion.PartnerID);
        }

        public ActionResult DeletePromotionList(string ids, string partnerId)
        {
            Message msg = promotionDao.DeleteList(ids);
            ShowMessage(msg);
            return RedirectToAction("Promotion/" + partnerId);
        }

        public ActionResult ActivePromotion(string id, string partnerId)
        {           
            Message msg = promotionDao.ActivePrmotion(id);
            return RedirectToAction("Promotion/" + partnerId);
        }

        public ActionResult Gallery(int id)
        {
            Partner partner = partnerDao.GetByID(id);
            if (partner != null)
            {
                ViewData["PartnerName"] = partner.PartnerName;
                ViewData["PartnerID"] = id.ToString();
            }            
            return View();
        }

        /// <summary>
        /// Get and bind to grid
        /// </summary>
        /// <param name="optionSearch"></param>
        /// <returns></returns>
        public ActionResult GetListGalleryJQGrid(string id)
        {
            //grid constant => duy hung
            if (string.IsNullOrEmpty(id))
            {
                return null;
            }
            else
            {
                #region JQGrid Params

                string sortColumn = (Request.Params[Constants.SORT_COLUMN]).ToString();
                string sortOrder = (Request.Params[Constants.SORT_ORDER]).ToString();
                int pageIndex = Convert.ToInt32(Request.Params[Constants.PAGE_INDEX]);
                int rowCount = Convert.ToInt32(Request.Params[Constants.ROW_COUNT]);

                #endregion

                List<Gallery> list = galDao.GetListByPartnerId(int.Parse(id));

                int totalRecords = list.Count();
                int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rowCount);
                int currentPage = pageIndex;
                var finalList = list.Skip((currentPage - 1) * rowCount).Take(rowCount);

                string labelPhoto = "<a id='thumb{0}' href='" + Constants.PHOTO_PATH_ROOT_PARTNER + "{1}"
                                                    + "' class='highslide' onclick='return hs.expand(this)'>"
                                                    + "<img id='imgPhoto' src='" + Constants.PHOTO_PATH_ROOT_PARTNER + "{2}"
                                                    + "' alt='Highslide JS' title='Nhấp vào để phóng to' height='150px'/></a>";

                var jsonData = new
                {
                    total = totalPages,
                    page = currentPage,
                    records = totalRecords,
                    rows = (
                        from m in finalList
                        select new
                        {
                            i = m.ID,
                            cell = new string[] {
                            m.ID.ToString(),
                            m.ImageOrder.ToString(),
                            string.Format(labelPhoto,m.ID, m.Image, m.Image),                            
                            "<input type='button' name='btnMoveUp' class='icon moveup' title='Move up' onclick=\"JS_LIB.redirect('/Administration/Partner/MoveImageDown/?id=" + m.ID.ToString() + "&partnerId=" + id +"')\" />"
                            +"<input type='button' name='btnMoveDown' class='icon movedown' title='Move down' onclick=\"JS_LIB.redirect('/Administration/Partner/MoveImageUp/?id=" + m.ID.ToString() + "&partnerId=" + id + "')\"/>"
                        }
                        }
                    ).ToArray()
                };
                return Json(jsonData, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult ShowFrontEnd(string id, string partnerId)
        {
            if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(id))
            {
                Message msg = galDao.UpdateActive(int.Parse(id));
            }
            return RedirectToAction("Gallery/" + partnerId);
        }

        public ActionResult MoveImageUp(string id, string partnerId)
        {
            Gallery gallery = galDao.GetById(int.Parse(id));
            Message msg = galDao.MoveUp(gallery);
            return RedirectToAction("Gallery/" + partnerId);
        }

        public ActionResult MoveImageDown(string id, string partnerId)
        {
            Gallery gallery = galDao.GetById(int.Parse(id));
            Message msg = galDao.MoveDown(gallery);
            return RedirectToAction("Gallery/" + partnerId);
        }

        public ActionResult CreateGallery(int id)
        {
            ViewData["PartnerID"] = id.ToString();
            return View();
        }

        private Message CheckUploadFile(HttpPostedFileBase file, string allowExt)
        {
            Message msg = null;
            string ext = Path.GetExtension(file.FileName);
            int maxSize = 1024 * 1024 * Constants.UPLOAD_FILE_SIZE;
            float sizeFile = float.Parse(file.ContentLength.ToString("N"));
            if (file.ContentLength < 0)
            {
                msg = new Message(MessageConstants.E0011, MessageType.Error);
            }
            else if (sizeFile > maxSize)
            {
                msg = new Message(MessageConstants.E0012, MessageType.Error, Constants.UPLOAD_FILE_SIZE);
            }
            else if (!allowExt.Split(',').Contains(ext))
            {
                msg = new Message(MessageConstants.E0013, MessageType.Error, ext, allowExt, Constants.UPLOAD_FILE_SIZE);
            }
            return msg;

        }

        [HttpPost]
        public FileUploadJsonResult UploadSingleImage(FormCollection form)
        {
            var principal = HttpContext.User as AuthenticationProjectPrincipal;
            FileUploadJsonResult result = new FileUploadJsonResult();
            Message msg = null;
            foreach (string file in Request.Files)
            {
                string uniqueId = DateTime.Now.ToString("MMddyyyyhhmmss");
                HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;

                if (hpf.ContentLength != 0)
                {
                    msg = CheckUploadFile(hpf, Constants.UPLOAD_ALLOW_IMG_EXT);

                    if (msg == null) //check successfull
                    {
                        string strPath = Server.MapPath(Constants.PHOTO_PATH_ROOT_PARTNER);
                        string imageName = uniqueId + "_" + Path.GetFileName(hpf.FileName);
                        hpf.SaveAs(strPath + imageName);

                        Gallery gallery = new Gallery();
                        gallery.Image = imageName;
                        gallery.PartnerID = int.Parse(form["PartnerID"]);
                        gallery.IsShownFrontEnd = true;
                        msg = galDao.Insert(gallery);
                        result.Data = new { msg };
                    }
                    else  //error case
                    {
                        result.Data = new { msg };

                    }
                }
                else
                {
                    msg = new Message(MessageConstants.E0011, MessageType.Error);
                    result.Data = new { msg };
                }
            }
            return result;
        }

        public ActionResult DeleteGalleryList(string ids, string partnerId)
        {
            Message msg = galDao.DeleteList(ids);
            ShowMessage(msg);
            return RedirectToAction("Gallery/" + partnerId);
        }
    }
}
